package com.xcd.reggie.controller;

import com.xcd.reggie.common.BaseContext;
import com.xcd.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.path}")
    private String basePath;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        log.info("basePath: {}", basePath);
        String filename;
        String originalFilename = file.getOriginalFilename();
        log.info("上传的文件：{}", file.getOriginalFilename());
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        UUID uuid = UUID.randomUUID();
        filename = uuid.toString() + suffix;

        File file1 = new File(basePath);


        if (!file1.exists()) {
            file1.mkdirs();
        }
        log.info("修改后的文件名为{}", filename);
        try {
            file.transferTo(new File(basePath + filename));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
//        try {
//            file.transferTo(new File("C:\\study\\img\\hello.jpg"));
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
        return R.success(filename);
    }

    @RequestMapping("/download")
    public void download(String name, HttpServletResponse response) {
        log.info("请求下载的文件；{}",name);
        try {
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));

            int len = 0;
            byte[] bytes = new byte[1024];

            while ((len = fileInputStream.read(bytes)) != -1) {
                ServletOutputStream outputStream = response.getOutputStream();
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
